/* eslint-disable no-param-reassign */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
// eslint-disable-next-line no-unused-vars
import { Card, Button, Col, Row, Input, message, Divider, Radio, Select } from 'antd';
import router from 'umi/router';
import FooterToolbar from '@/components/FooterToolbar';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { isRepeat } from '@/utils/utils';
import DictCode from '../../components/DictCode';
import Area from '../../components/Area';
import TableForm from './TableForm';
import HOCSelect from '@/components/AntDesign/Select';

const FormItem = Form.Item;
const { TextArea } = Input;
const RadioGroup = Radio.Group;
const { Option } = Select;

@connect(({ loading, detexport }) => ({
  loading: loading.effects['detexport/submit'],
  projectList: detexport.projectList,
  dataSource: detexport.dataSource,
  tableId: detexport.tableId,
  declDetailVo: detexport.declDetailVo,
  ADD_JOIN_TYPE: detexport.joinTypeList,
}))
@Form.create()
class TableList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      isIns: false, // 是否选择社保
      isInsUnify: true, // 五险合一
      isAddEmp: true, // 是否增员
      declDetailId: null,
      areaId: '',
      product: '',
    };
  }

  componentDidMount() {
    const {
      dispatch,
      location: { query },
    } = this.props;
    const { declDetailId } = query;

    if (declDetailId) {
      this.setState({ declDetailId });
      dispatch({
        type: 'detexport/fetchUpdateInfo',
        payload: { declDetailId },
        callback: data => {
          if (data.declDetailVo.type === 2) {
            this.setState({ isAddEmp: false });
          }
          if (data.declDetailVo.ass === '2') {
            dispatch({
              type: 'detexport/fetchJoinTypeList',
              // eslint-disable-next-line block-scoped-var
              payload: { pdId: 'PDINF_0000000002' },
            });
            this.setState({ isIns: false, isInsUnify: false });
            dispatch({
              type: 'detexport/fetchProjectLists',
              payload: { ass: '2', areaId: data.declDetailVo && data.declDetailVo.areaId },
            });
          } else {
            this.setState({ isIns: true, isInsUnify: data.declDetailVo.ass.indexOf('1') > -1 });
            dispatch({
              type: 'detexport/fetchJoinTypeList',
              // eslint-disable-next-line block-scoped-var
              payload: { pdId: 'PDINF_0000000001' },
            });
            dispatch({
              type: 'detexport/fetchJoinTypeList',
              // eslint-disable-next-line block-scoped-var
              payload: { pdId: 'PDINF_0000000001' },
            });
            dispatch({
              type: 'detexport/fetchProjectLists',
              payload: { ass: '1', areaId: data.declDetailVo && data.declDetailVo.areaId },
            });
          }
        },
      });
    } else {
      dispatch({
        type: 'detexport/setUpdateInfo',
        payload: {
          declDetailCols: [
            {
              key: 0,
              matId: undefined,
              colName: undefined,
              colCustomName: undefined,
            },
          ],
          declDetailVo: {},
        },
      });
    }
    // dispatch({
    //   type: 'detexport/fetchProjectList',
    // });
  }

  // 选择执行地
  selectArea = areaId => {
    const { dispatch } = this.props;
    const { product } = this.state;
    this.setState({
      areaId,
    });
    dispatch({
      type: 'detexport/fetchInsUnifyFlag',
      payload: { areaId },
      callback: data => {
        this.setState({ isInsUnify: data.insUnifyFlag ? data.insUnifyFlag === 1 : true });
      },
    });

    const paramet = {
      ass: product,
      areaId,
    };
    if (product && areaId) {
      dispatch({
        type: 'detexport/fetchProjectLists',
        payload: paramet,
      });
    }
  };

  typeName = () => {
    const { dispatch } = this.props;
    const { product } = this.state;
    dispatch({
      type: 'detexport/fetchJoinTypeList',
      // eslint-disable-next-line block-scoped-var
      payload: { pdId: product === '1' ? 'PDINF_0000000001' : 'PDINF_0000000002' },
    });
  };

  // 更改数据源
  changeDataSource = (dataSource, tableId) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'detexport/updateDataSource',
      payload: { dataSource, tableId },
    });
  };

  // 移动行数
  onMove = (index, nextIndex) => {
    const { dataSource, dispatch } = this.props;
    dispatch({
      type: 'detexport/onMove',
      payload: { index, nextIndex, dataSource },
    });
  };

  // 获取产品
  changeInsurance = e => {
    this.setState({ isIns: e.target.value === '1', product: e.target.value });
    const { dispatch, declDetailVo } = this.props;
    const { areaId } = this.state;
    const paramet = {
      ass: e.target.value,
      areaId,
    };
    declDetailVo.subTypeList = [];
    dispatch({
      type: 'detexport/updateModelData',
      payload: { declDetailVo, joinTypeList: [] },
    });

    if (areaId && e.target.value) {
      dispatch({
        type: 'detexport/fetchProjectLists',
        payload: paramet,
      });
    }
  };

  // 提交数据
  submitData = () => {
    const { dispatch, form, declDetailVo, dataSource } = this.props;
    const { declDetailId } = this.state;
    form.validateFields((err, values) => {
      if (!err) {
        if (declDetailId) {
          values.areaId = declDetailVo.areaId;
          values.vno = declDetailVo.vno;
          const declDetailCols = [];
          // eslint-disable-next-line no-unused-vars
          Object.entries(values.declDetailCols).forEach(([key, value]) => {
            declDetailCols.push(value);
          });
          values.declDetailCols = declDetailCols;
        }
        values.declDetailCols = values.declDetailCols.filter(item => item);
        if (isRepeat(values.declDetailCols, 'matId')) {
          message.warning('所选项目名称重复，请重新选择！');
          return;
        }
        const submitDataSourse = [];
        dataSource.forEach(item => {
          submitDataSourse.push({
            matId: item.matId,
            colCustomName: item.colCustomName,
          });
        });
        values.declDetailCols = submitDataSourse;
        dispatch({
          type: 'detexport/submit',
          payload: { values, declDetailId },
        });
      }
    });
  };

  render() {
    const {
      loading,
      projectList,
      dataSource,
      tableId,
      declDetailVo,
      form,
      ADD_JOIN_TYPE,
    } = this.props;
    const { getFieldDecorator } = form;
    const { declDetailId, isIns, isInsUnify, isAddEmp } = this.state;
    return (
      <Form layout="horizontal">
        <PageHeaderWrapper>
          <Card
            title={
              <span style={{ fontWeight: 'bolder' }}>
                {declDetailId ? '修改' : '新增'}申报明细表模板
              </span>
            }
            style={{ borderBottom: 'none' }}
          >
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
              <Col md={8} sm={24}>
                <FormItem
                  label="名称"
                  labelCol={{ md: { span: 7 } }}
                  wrapperCol={{ md: { span: 17 } }}
                >
                  {getFieldDecorator('declDetailName', {
                    rules: [{ required: true, message: '请输入', max: 100 }],
                    initialValue: declDetailVo.declDetailName || undefined,
                  })(<Input placeholder="请输入" maxLength={100} />)}
                </FormItem>
              </Col>
              <Col md={8} sm={24}>
                <FormItem
                  label="执行地"
                  labelCol={{ md: { span: 7 } }}
                  wrapperCol={{ md: { span: 17 } }}
                >
                  {getFieldDecorator('areaId', {
                    rules: [{ required: true, message: '请选择' }],
                    initialValue: declDetailVo.areaName || undefined,
                  })(<Area onChange={this.selectArea} disabled={declDetailId !== null} />)}
                </FormItem>
              </Col>
              <Col md={8} sm={24}>
                <FormItem
                  label="备注"
                  labelCol={{ md: { span: 7 } }}
                  wrapperCol={{ md: { span: 17 } }}
                >
                  {getFieldDecorator('remark', {
                    rules: [{ required: false, message: '最多不超过100字符', max: 200 }],
                    initialValue: declDetailVo.remark || undefined,
                  })(<TextArea placeholder="请输入" rows={1} maxLength={200} />)}
                </FormItem>
              </Col>
            </Row>
            {/* <Divider /> */}
            <div style={{ borderTop: '1px dashed #ccc', marginBottom: '32px' }} />

            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
              <Col md={8} sm={24}>
                <FormItem
                  label="产品"
                  labelCol={{ md: { span: 7 } }}
                  wrapperCol={{ md: { span: 17 } }}
                >
                  {getFieldDecorator('insAccu', {
                    rules: [{ required: true, message: '请选择' }],
                    initialValue:
                      (declDetailVo.ass && (declDetailVo.ass.indexOf('2') === -1 ? '1' : '2')) ||
                      undefined,
                  })(
                    <RadioGroup
                      options={[{ value: '1', label: '社保' }, { value: '2', label: '公积金' }]}
                      // onChange={e => {
                      //   this.setState({ isIns: e.target.value === '1' });
                      // }}
                      onChange={e => {
                        this.changeInsurance(e);
                      }}
                      disabled={declDetailId !== null}
                    />
                  )}
                </FormItem>
              </Col>
            </Row>
            {isIns && !isInsUnify ? (
              <div>
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                  <Col md={13} sm={24}>
                    <FormItem
                      label="险种"
                      labelCol={{ md: { span: 4 } }}
                      wrapperCol={{ md: { span: 20 } }}
                    >
                      {getFieldDecorator('ass', {
                        rules: [{ required: true, message: '请选择' }],
                        initialValue: declDetailVo.insAccu || [],
                      })(
                        <DictCode
                          inputType="2"
                          dictType="BIZ_INS_TYPE"
                          // disabled={declDetailId !== null}
                        />
                      )}
                    </FormItem>
                  </Col>
                </Row>
                <Row style={{ width: '900px', margin: '0 0 32px 6%', color: '#999999' }}>
                  注：五险不合一的地区请根据大库或单立户中险种配置情况勾选社保险种。例如：该地区有一个大库配置了支持医疗和生育，则可同时选择医疗和生育，申报明细表导出时医疗和生育也会在同一张申报明细表；同理有一个大库只配置了养老，则需新建另外一个只选择的养老的模版配置申报明细表；确保险种一致是大库或单立户找申报明细表模版的必要条件。
                </Row>
              </div>
            ) : null}
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
              <Col md={8} sm={24}>
                <FormItem
                  label="申报类型"
                  labelCol={{ md: { span: 7 } }}
                  wrapperCol={{ md: { span: 17 } }}
                >
                  {getFieldDecorator('type', {
                    rules: [{ required: true, message: '请选择' }],
                    initialValue: declDetailVo.type || undefined,
                  })(
                    <RadioGroup
                      options={[{ value: 1, label: '增员' }, { value: 2, label: '减员' }]}
                      onChange={e => {
                        this.setState({ isAddEmp: e.target.value === 1 });
                      }}
                      disabled={declDetailId !== null}
                    />
                  )}
                </FormItem>
              </Col>
            </Row>
            {isAddEmp ? (
              <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={8} sm={24}>
                  {/* <FormItem
                    label="参保类型"
                    labelCol={{ md: { span: 7 } }}
                    wrapperCol={{ md: { span: 17 } }}
                  >
                    {getFieldDecorator('subType', {
                      rules: [{ required: true, message: '请选择' }],
                      initialValue: declDetailVo.subType || undefined,
                    })(
                      // <DictCode
                      //   dictType="ADD_JOIN_TYPE"
                      //   mode="multiple"
                      //   disabled={declDetailId !== null}
                      // />
                      <Select
                        placeholder="请选择"
                        style={{ width: 220 }}
                        mode="multiple"
                        disabled={declDetailId !== null}
                        onFocus={() => this.typeName()}
                      >
                        {ADD_JOIN_TYPE.map(item => (
                          <Option key={item.itemCode}>{item.itemName}</Option>
                        ))}
                      </Select>
                    )}
                  </FormItem> */}

                  {declDetailVo.subType ? (
                    <FormItem
                      label="参保类型"
                      labelCol={{ md: { span: 7 } }}
                      wrapperCol={{ md: { span: 17 } }}
                    >
                      {getFieldDecorator('subType', {
                        rules: [{ required: true, message: '请选择' }],
                        initialValue: declDetailVo.subType || undefined,
                      })(
                        <HOCSelect
                          placeholder="请选择"
                          style={{ width: 220 }}
                          mode="multiple"
                          disabled={declDetailId !== null}
                          onFocus={() => this.typeName()}
                        >
                          {declDetailVo &&
                            declDetailVo.subTypeList &&
                            declDetailVo.subTypeList.map(item => (
                              <Option key={item.itemCode}>{item.itemName}</Option>
                            ))}
                        </HOCSelect>
                      )}
                    </FormItem>
                  ) : (
                    <FormItem
                      label="参保类型"
                      labelCol={{ md: { span: 7 } }}
                      wrapperCol={{ md: { span: 17 } }}
                    >
                      {getFieldDecorator('subType', {
                        rules: [{ required: true, message: '请选择' }],
                        initialValue: declDetailVo.subType || undefined,
                      })(
                        <HOCSelect
                          placeholder="请选择"
                          style={{ width: 220 }}
                          mode="multiple"
                          onFocus={() => this.typeName()}
                        >
                          {ADD_JOIN_TYPE.map(item => (
                            <Option key={item.itemCode}>{item.itemName}</Option>
                          ))}
                        </HOCSelect>
                      )}
                    </FormItem>
                  )}
                </Col>
              </Row>
            ) : null}
            {/* <Divider /> */}

            <div style={{ borderTop: '1px dashed #ccc', marginBottom: '32px' }} />
            <TableForm
              projectList={projectList}
              datas={dataSource}
              tableId={tableId}
              changeDataSource={this.changeDataSource}
              onMove={this.onMove}
              form={form}
            />
          </Card>
          <FooterToolbar style={{ width: '100%' }}>
            <Button
              onClick={() => router.push('/systemsetting/detexport/index')}
              style={{ marginRight: 10 }}
            >
              取消
            </Button>
            <Button type="primary" onClick={this.submitData} loading={loading}>
              保存
            </Button>
          </FooterToolbar>
        </PageHeaderWrapper>
      </Form>
    );
  }
}

export default TableList;
